package zhoug.zui;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import zhoug.common.interfaces.OnExpandChangeListener;
import zhoug.logging.Logger;
import zhoug.common.utils.ResourceUtils;
import zhoug.common.utils.SoftInputMethodManager;
import zhoug.common.utils.TextUtils;
import zhoug.zui.ints.OnSearchListener;
import zhoug.zui.utils.ZUIUtils;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 搜索框
 * 全局样式定义:zui_style_ZUISearchView
 * 支持左右图标,清除图标,图标大小,个性化光标,背景,文字样式
 *
 * @Author 35574
 * @Date 2020/7/30
 * @Description
 */
public class ZUISearchView extends FrameLayout {
    private static final String TAG = ">>>ZUISearchView";
    private static final boolean DEBUG = false;

    private EditText mEditText;
    private ImageView mLeftImage;
    private ZUIExpandView mLeftExpandView;
    private ImageView mRightImage;
    private ImageView mClearImage;
    private View root;
    private OnSearchListener onSearchListener;
    private @DrawableRes
    int leftIcon; //左边图标
    private @DrawableRes
    int rightIcon;//右边图标
    private @DrawableRes
    int clearIcon;//清除图标

    private int mDefHeight;//默认高度
    private boolean mInvokeCallback = true;//是否触发回调
    private boolean mMulti;

    public ZUISearchView(Context context) {
        this(context, null);
    }

    public ZUISearchView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, R.attr.ZUISearchView_theme);
    }

    public ZUISearchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);

    }

    /**
     * 初始化
     *
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    private void init(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ZUISearchView, defStyleAttr, R.style.ZUISearchView_def);
        leftIcon = a.getResourceId(R.styleable.ZUISearchView_zui_leftIcon, ZUIUtils.UN_USED_RES_ID);
        rightIcon = a.getResourceId(R.styleable.ZUISearchView_zui_rightIcon, ZUIUtils.UN_USED_RES_ID);
        clearIcon = a.getResourceId(R.styleable.ZUISearchView_zui_clearIcon, ZUIUtils.UN_USED_RES_ID);
        //背景
        int background = a.getResourceId(R.styleable.ZUISearchView_zui_background, ZUIUtils.UN_USED_RES_ID);
        //光标
        int cursorDrawableRes = a.getResourceId(R.styleable.ZUISearchView_zui_textCursorDrawable, ZUIUtils.UN_USED_RES_ID);
        //图片大小
        int iconSize = a.getDimensionPixelOffset(R.styleable.ZUISearchView_zui_iconSize, -1);
        int clearIconSize = a.getDimensionPixelOffset(R.styleable.ZUISearchView_zui_clearIconSize, -1);
        int leftIconSize = a.getDimensionPixelOffset(R.styleable.ZUISearchView_zui_leftIconSize, -1);
        int rightIconSize = a.getDimensionPixelOffset(R.styleable.ZUISearchView_zui_rightIconSize, -1);
        float textSize = a.getDimension(R.styleable.ZUISearchView_zui_textSize, -1);
        int textColor = a.getColor(R.styleable.ZUISearchView_zui_textColor, ZUIUtils.UN_USED_COLOR);
        int hintColor = a.getColor(R.styleable.ZUISearchView_zui_hintColor, ZUIUtils.UN_USED_COLOR);
        String hintText = a.getString(R.styleable.ZUISearchView_zui_hintText);
        mDefHeight = a.getDimensionPixelOffset(R.styleable.ZUISearchView_zui_height, 0);
        int editTextMarginLeft = a.getDimensionPixelOffset(R.styleable.ZUISearchView_zui_editTextMarginLeft, 0);
        int editTextMarginRight = a.getDimensionPixelOffset(R.styleable.ZUISearchView_zui_editTextMarginRight, 0);
        boolean multi = a.getBoolean(R.styleable.ZUISearchView_zui_multi, false);
        int expandTextColor = a.getColor(R.styleable.ZUISearchView_zui_expandTextColor, 0);
        float expandTextSize = a.getDimension(R.styleable.ZUISearchView_zui_expandTextSize, 0);
        int expandTextStyle = a.getInt(R.styleable.ZUISearchView_zui_expandTextStyle, Typeface.NORMAL);
        int expandIconDrawableExpand = a.getResourceId(R.styleable.ZUISearchView_zui_expandIconDrawableExpand, R.drawable.zui_icon_expand_expand);
        int expandIconDrawable = a.getResourceId(R.styleable.ZUISearchView_zui_expandIconDrawable, R.drawable.zui_icon_expand_normal);
        int expandIconSize = a.getDimensionPixelSize(R.styleable.ZUISearchView_zui_expandIconSize, 0);
        ColorStateList expandIconTint = a.getColorStateList(R.styleable.ZUISearchView_zui_expandIconTint);
        int expandDrawablePadding = a.getDimensionPixelOffset(R.styleable.ZUISearchView_zui_expandDrawablePadding, ResourceUtils.dpTopx(5));
        boolean expandTextSingleLine = a.getBoolean(R.styleable.ZUISearchView_zui_expandTextSingleLine, true);
        int expandBackground = a.getResourceId(R.styleable.ZUISearchView_zui_expandBackground, 0);
        int expandViewWidth = a.getLayoutDimension(R.styleable.ZUISearchView_zui_expandViewWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
        int expandViewPaddingStart = a.getDimensionPixelSize(R.styleable.ZUISearchView_zui_expandViewPaddingStart, 0);
        int expandViewPaddingTop = a.getDimensionPixelSize(R.styleable.ZUISearchView_zui_expandViewPaddingTop, 0);
        int expandViewPaddingEnd = a.getDimensionPixelSize(R.styleable.ZUISearchView_zui_expandViewPaddingEnd, 0);
        int expandViewPaddingBottom = a.getDimensionPixelSize(R.styleable.ZUISearchView_zui_expandViewPaddingBottom, 0);


        a.recycle();


        if (mDefHeight <= 0) {
            mDefHeight = getContext().getResources().getDimensionPixelOffset(R.dimen.zui_searchView_height);
        }

        root = LayoutInflater.from(context).inflate(R.layout.zui_search_view, this, false);
        //设置背景
        setBackground(background);

        mLeftExpandView = root.findViewById(R.id.search_expandView);
        mLeftImage = root.findViewById(R.id.icon_left);
        mRightImage = root.findViewById(R.id.icon_right);
        mClearImage = root.findViewById(R.id.icon_clear);
        mEditText = root.findViewById(R.id.et_input);
        //设置图片尺寸
        if (iconSize > 0 || leftIconSize > 0) {
            if (leftIconSize > 0) {
                setImageSize(mLeftImage, leftIconSize);
            } else {
                setImageSize(mLeftImage, iconSize);
            }
        }
        if (iconSize > 0 || rightIconSize > 0) {
            if (rightIconSize > 0) {
                setImageSize(mRightImage, rightIconSize);
            } else {
                setImageSize(mRightImage, iconSize);
            }
        }
        if (iconSize > 0 || clearIconSize > 0) {
            if (clearIconSize > 0) {
                setImageSize(mClearImage, clearIconSize);
            } else {
                setImageSize(mClearImage, iconSize);
            }
        }

        //设置图片
        setLeftIcon(leftIcon);
        setRightIcon(rightIcon);
        //设置光标
        if (cursorDrawableRes != ZUIUtils.UN_USED_RES_ID) {
            TextUtils.setTextCursorDrawable(mEditText, cursorDrawableRes);
        }
        if (clearIcon != ZUIUtils.UN_USED_RES_ID) {
            mClearImage.setImageResource(clearIcon);
        }
        if (DEBUG) {
            Logger.d(TAG, "init:leftIcon=" + leftIcon);
            Logger.d(TAG, "init:rightIcon=" + rightIcon);
            Logger.d(TAG, "init:clearIcon=" + clearIcon);
            Logger.d(TAG, "init:cursorDrawableRes=" + cursorDrawableRes);
        }


        //设置EditText和左右图标的距离
        ViewGroup.LayoutParams layoutParams = mEditText.getLayoutParams();
        if (layoutParams instanceof MarginLayoutParams) {
            MarginLayoutParams params = (MarginLayoutParams) layoutParams;
            params.leftMargin = editTextMarginLeft;
            params.rightMargin = editTextMarginRight;
            mEditText.setLayoutParams(params);
        }
        //设置文本样式
        setTextColor(textColor);
        setTextSize(textSize);
        setHintTextColor(hintColor);
        if (hintText != null) {
            mEditText.setHint(hintText);
        }
        //左边ZUIExpandView属性设置
        if (expandTextColor != 0) {
            mLeftExpandView.setTextColor(expandTextColor);
            mLeftExpandView.setExpandTextColor(expandTextColor);
        }
        if (expandTextSize != 0) {
            mLeftExpandView.setTextSize(expandTextSize);
        }
        mLeftExpandView.setTypeface(expandTextStyle);
        mLeftExpandView.setIconRes(expandIconDrawable);
        mLeftExpandView.setExpandIconRes(expandIconDrawableExpand);
        if (expandIconSize != 0) {
            mLeftExpandView.setIconSize(expandIconSize);
        }
        mLeftExpandView.setIconTint(expandIconTint);
        mLeftExpandView.setDrawablePadding(expandDrawablePadding);
        mLeftExpandView.setSingleLine(expandTextSingleLine);
        if (expandBackground != 0) {
            mLeftExpandView.setBackgroundResource(expandBackground);
        }
        ViewGroup.LayoutParams expandViewLayoutParams = mLeftExpandView.getLayoutParams();
        if (expandViewLayoutParams != null) {
            expandViewLayoutParams.width = expandViewWidth;
        }

        mLeftExpandView.setPadding(expandViewPaddingStart, expandViewPaddingTop, expandViewPaddingEnd, expandViewPaddingBottom);


        setMulti(multi);
        addView(root);
        init();
    }

    public void setMulti(boolean multi) {
        if (this.mMulti != multi) {
            this.mMulti = multi;
            if (this.mMulti) {
                mLeftExpandView.setVisibility(VISIBLE);
                mLeftImage.setVisibility(GONE);
            } else {
                mLeftExpandView.setVisibility(GONE);
                Drawable drawable = mLeftImage.getDrawable();
                if (drawable != null) {
                    mLeftExpandView.setVisibility(VISIBLE);
                } else {
                    mLeftExpandView.setVisibility(GONE);
                }
            }
        }
    }

    /**
     * 设置图片尺寸
     *
     * @param imageView
     * @param iconSize
     */
    private void setImageSize(ImageView imageView, int iconSize) {
        ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
        if (layoutParams != null) {
            layoutParams.width = iconSize;
            layoutParams.height = iconSize;
            imageView.setLayoutParams(layoutParams);
        }
    }


    /**
     * 软键盘按钮监听
     */
    private TextView.OnEditorActionListener onEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            int searchId = getResources().getInteger(R.integer.zui_ime_search_id);
            if (actionId == searchId || actionId == EditorInfo.IME_ACTION_SEARCH) {
                startSearch();
                return true;
            }
            return false;
        }
    };

    /**
     * 监听
     */
    private void init() {
        mEditText.setOnFocusChangeListener((v, hasFocus) -> {
            Logger.d(TAG, "hasFocus:"+hasFocus);
            if (root != null && root.getBackground() != null) {
                Drawable background = root.getBackground();
                if (background instanceof StateListDrawable stateListDrawable) {
                    if (hasFocus) {
                        stateListDrawable.setState(new int[]{android.R.attr.state_focused});
                    } else {
                        stateListDrawable.setState(new int[]{});
                    }
                }

            }
            if (clearIcon != ZUIUtils.UN_USED_RES_ID) {
                Editable text = mEditText.getText();
                if (hasFocus && text != null && !text.toString().isEmpty()) {
                    mClearImage.setVisibility(VISIBLE);
                } else {
                    mClearImage.setVisibility(GONE);
                }
            }
            if (mMulti && mLeftExpandView.getBackground() != null) {
                Drawable background = mLeftExpandView.getBackground();
                if(background instanceof StateListDrawable stateListDrawable){
                    stateListDrawable.setState(hasFocus ? new int[]{android.R.attr.state_focused} : new int[]{});
                }

            }


        });
        mEditText.setOnEditorActionListener(onEditorActionListener);
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s != null && !s.toString().isEmpty()) {
                    //有输入的情况
                    //显示清除按钮
                    if (clearIcon != ZUIUtils.UN_USED_RES_ID) {
                        if (mEditText.hasFocus() && mClearImage.getVisibility() != VISIBLE) {
                            mClearImage.setVisibility(VISIBLE);
                        }
                        //隐藏右边图片
                        if (mRightImage.getVisibility() == View.VISIBLE) {
                            mRightImage.setVisibility(GONE);
                        }
                    } else {
                        //没有清除按钮
                        if (rightIcon != ZUIUtils.UN_USED_RES_ID) {
                            //显示右边图片
                            if (mRightImage.getVisibility() != View.VISIBLE) {
                                mRightImage.setVisibility(VISIBLE);
                            }
                        }
                    }
                    if (mInvokeCallback && onSearchListener != null) {
                        onSearchListener.onInputChange(s.toString());
                    }
                } else {
                    //没有输入的情况
                    //隐藏清除按钮
                    if (mClearImage.getVisibility() == VISIBLE) {
                        mClearImage.setVisibility(GONE);
                    }
                    if (rightIcon != ZUIUtils.UN_USED_RES_ID) {
                        //显示右边图片
                        if (mRightImage.getVisibility() != View.VISIBLE) {
                            mRightImage.setVisibility(VISIBLE);
                        }
                    }
                    if (mInvokeCallback && onSearchListener != null) {
                        onSearchListener.onClear();
                    }
                }


            }
        });
        //清除按钮监听
        mClearImage.setOnClickListener(v -> {
            setInput(null);
            if (onSearchListener != null) {
                onSearchListener.onClear();
            }
        });

    }

    /**
     * 开始搜索
     * 可以主动调用,比如在页面上添加一个按钮,点击按钮调用开始搜索
     */
    public void startSearch() {
        if (mEditText != null) {
            mEditText.clearFocus();
            clearFocus();
        }
//        if (getContext() instanceof Activity) {
//            AppUtils.hideSoftKeyboard((Activity) getContext());
//        }
        //关闭软键盘
        new SoftInputMethodManager(getContext()).hideSoftInput(this);
        if (onSearchListener != null) {
            onSearchListener.onSearch(getInput());
        }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightMode == MeasureSpec.AT_MOST) {
            int height = Math.min(mDefHeight + getPaddingTop() + getPaddingBottom(), MeasureSpec.getSize(heightMeasureSpec));
            if (DEBUG) {
                Logger.d(TAG, "onMeasure:height=" + height);
            }
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
        } else if (heightMode == MeasureSpec.UNSPECIFIED) {
            int height = mDefHeight + getPaddingTop() + getPaddingBottom();
            if (DEBUG) {
                Logger.d(TAG, "onMeasure:height=" + height);
            }
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    /**
     * 设置搜索监听器
     *
     * @param onSearchListener
     */
    public void setOnSearchListener(OnSearchListener onSearchListener) {
        this.onSearchListener = onSearchListener;
    }

    /**
     * 设置提示文字
     *
     * @param hintText
     */
    public void setHintText(CharSequence hintText) {
        if (mEditText != null) {
            mEditText.setHint(hintText);
        }
    }

    public void setHintTextColor(int hintColor) {
        ZUIUtils.setHintTextColor(mEditText, hintColor);
    }

    public void setTextColor(int textColor) {
        ZUIUtils.setTextColor(mEditText, textColor);
    }

    public void setTextSize(float textSize) {
        ZUIUtils.setTextSize(mEditText, textSize);
    }


    /**
     * 设置输入的文字
     *
     * @param input
     */
    public void setInput(CharSequence input) {
        setInput(input, false);
    }

    /**
     * 设置输入的文字
     *
     * @param input
     */
    public void setInput(CharSequence input, boolean call) {
        if (mEditText != null) {
            if (call) {
                mEditText.setText(input);
            } else {
                mInvokeCallback = false;
                mEditText.setText(input);
                mInvokeCallback = true;
            }
            if (input != null) {
                mEditText.setSelection(input.length());
            }
        }
    }

    /**
     * 获取输入的文字
     *
     * @return
     */
    @NonNull
    public String getInput() {
        if (mEditText != null) {
            return mEditText.getText().toString();
        }
        return "";
    }


    public void setBackground(@DrawableRes int background) {
        //设置背景
        if (root != null && background != ZUIUtils.UN_USED_RES_ID) {
            root.setBackgroundResource(background);
        }
    }

    public EditText getEditText() {
        return mEditText;
    }

    public ImageView getLeftImage() {
        return mLeftImage;
    }

    public ImageView getRightImage() {
        return mRightImage;
    }

    public ImageView getClearImage() {
        return mClearImage;
    }

    public void setLeftIcon(@DrawableRes int leftIcon) {
        this.leftIcon = leftIcon;
        if (leftIcon != ZUIUtils.UN_USED_RES_ID) {
            mLeftImage.setImageResource(leftIcon);
            mLeftImage.setVisibility(VISIBLE);
        } else {
            mLeftImage.setVisibility(GONE);
        }
    }

    public void setRightIcon(@DrawableRes int rightIcon) {
        this.rightIcon = rightIcon;
        if (rightIcon != ZUIUtils.UN_USED_RES_ID) {
            mRightImage.setImageResource(rightIcon);
            mRightImage.setVisibility(VISIBLE);
        } else {
            mRightImage.setVisibility(GONE);
        }
    }


    public void setExpandName(String name) {
        mLeftExpandView.setName(name);
    }

    public void setOnExpandChangeListener(OnExpandChangeListener<ZUIExpandView> onExpandChangeListener) {
        mLeftExpandView.setOnExpandChangeListener(onExpandChangeListener);
    }

    public ZUIExpandView getLeftExpandView() {
        return mLeftExpandView;
    }

    public void setExpand(boolean expand) {
        mLeftExpandView.setExpanded(expand);
    }

}
